﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EGEHaina.Areas.General.Models;
using System.Collections;
using System.Data;
using EGEHaina.Library.Controllers;
using EGEHaina.Library.Session;
using EGEHaina.Models;

namespace EGEHaina.Areas.General.Controllers
{
    public class DepartmentController : BaseController
    {
        private EGEHainaContext db = new EGEHainaContext();
        //
        // GET: /General/Department/

        public ActionResult Index()
        {
            return RedirectToAction("Read");
        }

        public ActionResult Read()
        {
            db.Departments.ToList();
            return View();
        }

        /// <summary>
        /// Retorna un string formato json para cargar la grilla con los datos 
        /// </summary>
        /// <returns></returns>
        public JsonResult ReadItems()
        {
            int start = Convert.ToInt32( Request.QueryString["iDisplayStart"] );
            int limit = Convert.ToInt32( Request.QueryString["iDisplayLength"] );
            // query linq
            var query = (from d in db.Departments
                         orderby d.Name
                         select d).Skip(start).Take(limit);

            // query total records in table
            int total = (from d in db.Departments
                        select d).Count();

            IList departments = new ArrayList();
            foreach(Department item in query.ToList()) {
                string[] dep = new string[] { item.DepartmentId.ToString(), item.Name, item.Description, item.Created.ToString() };
                departments.Add(dep);
            }

            return Json(new { sEcho = Convert.ToInt32( Request.QueryString["sEcho"] ), 
                              iTotalRecords = total,
                              iTotalDisplayRecords = total,
                              aaData = departments,
                            }, JsonRequestBehavior.AllowGet);
        }

        public PartialViewResult Create()
        {
            return PartialView();
        }

        public JsonResult CreateSave(Department model)
        {
            //verificamos si los datos son validos
            if (ModelState.IsValid)
            {
                db.Departments.Add(model);
                db.SaveChanges();
                FlashMessage("Your entry was successfully saved.", FlashMessenger.MessageType.Success);
                return Json(new { success = true, message = "Your entry was successfully saved." });
            }
            else
            {
                // sacamos todos lo errores ocurridos en el modelo
                string errors = this.getErrors(ModelState);
                ViewData["error"] = ModelState.SelectMany(key => ModelState["Name"].Errors);
                return Json(new { success = false, message = errors });
            }
        }

        /// <summary>
        /// Carga un formulario con los datos del modelo
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PartialViewResult Update(int id) 
        {
            Department department = db.Departments.Find(id);
            return PartialView(department);
        }
        
        /// <summary>
        /// Actualiza los datos para el modelo
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonResult UpdateSave(Department model)
        {
            //verificamos si los datos son validos
            if (ModelState.IsValid)
            {
                db.Entry(model).State = EntityState.Modified;
                db.SaveChanges();
                FlashMessage("Your entry was successfully saved.", FlashMessenger.MessageType.Success);
                return Json(new { success = true, message = "Your entry was successfully saved." });
            }
            else
            {
                // sacamos todos lo errores ocurridos en el modelo
                string errors = this.getErrors(ModelState);
                ViewData["error"] = ModelState.SelectMany(key => ModelState["Name"].Errors);
                return Json(new { success = false, message = errors });
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete(Int32[] items)
        {
            try
            {
                foreach (var id in items)
                {
                    Department department = db.Departments.Find(id);
                    db.Departments.Remove(department);
                }
                db.SaveChanges();
                return Json(new { success = true, message = "Your data was successfully Deleted." });
            }
            catch (Exception ex) 
            {
                return Json(new { success = false, message = "An error occurred while processing the data. <br/> Please Try again."  });
            }
        }
    }
}
